package com.example.mall.common.core;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;

/**
 * 路由前缀根据路径自定补全
 *  - app启动时全部修改好,而不是在每次请求时处理。
 */
public class AutoPrefixUrlMapping extends RequestMappingHandlerMapping {
    @Value("${app.auto-prefix.api-package-name}")
    private String apiPackagePath;

    @Override
    protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
        /**
         * 修改思路:
         *  - 根据请求方法所在的文件路径,
         *  - 自定补全: 控制器的路径作为请求地址的一部分
         *  - 简化controller名的书写, exp: @RequestMapping("/v1/功能") -变成-> @RequestMapping("/功能")
         */
        RequestMappingInfo mappingInfo = super.getMappingForMethod(method, handlerType);

        String prefix = getPrefix(handlerType);
        if (prefix.contains("/") && prefix.startsWith("/")) {
            // 拼接上 接口上标注的地址, @RequestMapping("/地址")
            RequestMappingInfo info = RequestMappingInfo
                    .paths(prefix).build();
            RequestMappingInfo mappingInfo1 = info.combine(mappingInfo);
            return mappingInfo1;
        }

        return mappingInfo;
    }

    /**
     * 提取自定义接口的路径前缀
     * @param handlerType
     * @return
     */
    private String getPrefix(Class<?> handlerType) {
        String packageName = handlerType.getPackage().getName();
        if (packageName.contains(apiPackagePath) == false) {
            return packageName;
        }

        String packName = packageName.replaceAll(apiPackagePath, "");
        String dotPath = packName.replace(".", "/");
        if ("".equals(dotPath))
            dotPath = "/";
        return dotPath;
    }
}
